<?php
/**
 * Created by PhpStorm.
 * User: lingyun
 * Date: 2018/1/24
 * Time: 10:53
 * Desc: 首页  -- 不继承Base
 *       防止切换门店的时候
 */
namespace app\index\controller;
use think\Controller;
use think\Db;
use app\index\controller\Base;
use controller\BasicWechat;
use app\index\service\IndexService;
use pinyin\Pinyin;

class Index extends Controller{

    /**
     * @Author  lingyun
     * @Desc    查询当前是否选择门店
     */
    public function _initialize(){
        if(is_weixin()){    //微信端
            if(empty(session('openid'))) {
                $oauth = new BasicWechat();     //微信授权登录,获取openID
            }
        }

        $cookie_city_key = cookie('city_key');                          //城市key -- 拼音
        $cookie_city_code = cookie('city_code');                        //城市主键表示 -- code
        $cookie_store_id = cookie('store_id');                          //上次选中的门店
//        $cookie_store_id = '';
        $ip = request()->ip();                                      //获取客户端的IP地址
        $result = get_location_city($ip);                           //返回当前的城市信息
        $pinyin = new Pinyin();                                     //将中文装换成拼音
        $city_key = $pinyin->getAllPY($result['msg']);              //当前城市的key
        $city = db('city')->where('key',$city_key)->find();         //当前的城市信息
        $city_list = db('city')->where(['status'=>1,'is_deleted'=>0])->select();                //切换城市的城市列表

        if($cookie_city_key == '' || $cookie_city_code == '' || $cookie_store_id == ''){            //没有历史记录，重新获取
            $this->assign('is_cookie_city',0);                          //没有选择城市或者门店
        }else{
            cookie('city_key',$cookie_city_key,15552000);               //保存当前的城市代码
            cookie('city_code',$cookie_city_code,15552000);             //城市的代码
            cookie('store_id',$cookie_store_id,15552000);               //城市的代码
            session('store_id',$cookie_store_id);                       //记住门店id
            $this->assign('is_cookie_city',1);                          //已经选择城市或者门店
        }

        $service = new IndexService();
        $cart_num = $service->get_cart_amount();

        $cur_city = db('city')->where('key',cookie('city_key'))->value('value');                    //当前的城市名称

        $this->url = $this->request->url(true);       //登录回调页面
        $this->assign('url',$this->url);
        $this->assign('cur_city',$cur_city);          //当前城市名称
        $this->assign('cur_category',0);              //商品的顶级分类
        $this->assign('city_list',$city_list);        //城市列表
        $this->assign('cart_num',$cart_num);          //购物车数量
        $this->assign('wx_qrcode_img',sysconf('wechat_code_img'));
    }

    /**
     * @Author  lingyun
     * @Desc    空操作
     * @return string
     */
    public function _empty(){
        //把所有城市的操作解析到city方法
        return $this->fetch('public/404');
//        return '操作不存在';
    }

    /**
     * @Author  lingyun
     * @Desc    门店首页
     * @Desc    门店轮播图片、首次进入门店的会员领取门店关注券、门店推荐商品列表、门店推荐商品的分类
     * @Desc    订单详情表里面的goods_id关联ys_goods的主键  spec_id关联的是
     */
    public function index(){

        $service = new IndexService();

        $category = get_top_category();                                     //顶部导航栏
        $service->qy_coupon(1);                                             //会员权益优惠券
        $banner = $service->get_top_banner();                               //顶部轮播图
        $advert_1 = $service->get_advert_one();                             //广告位一
        $advert_2 = $service->get_advert_two();                             //广告位二
        $coupon = $service->get_store_coupon();                             //门店权益优惠券
        $recommend_category = $service->get_recommend_category();           //推荐商品分类
        $recommend_category_1 = $recommend_category['r_c_one'];             //推荐商品分类一
        $recommend_category_2 = $recommend_category['r_c_two'];             //推荐商品分类二
        $recommend_gooods = $service->get_recommend_category_goods();       //推荐商品
        $recommend_goods_1 = $recommend_gooods['r_g_one'];                  //推荐商品
        $recommend_goods_2 = $recommend_gooods['r_g_two'];                  //推荐商品
        $goods_label = $service->get_goods_label();                         //商品标签
        $tui_goods = $service->get_daohang_tui_goods();                         //顶部导航栏推荐商品
        $member = $service->get_member_info();                              //获取会员信息

        $this->assign('category',$category);                            //顶部商品分类导航
//        $this->assign('has_qy_coupon',$has_qy_coupon);                  //是否有权益优惠券
        $this->assign('banner',$banner);                                //顶部轮播图
        $this->assign('advert_1',$advert_1);                            //广告位一
        $this->assign('advert_2',$advert_2);                            //广告位二
//        $this->assign('count_coupon',count($coupon));                   //计算优惠券数量
        $this->assign('coupon',$coupon);                                //门店推荐关注券
        $this->assign('recommend_category_1',$recommend_category_1);    //推荐商品分类
        $this->assign('recommend_category_2',$recommend_category_2);    //推荐商品分类
        $this->assign('recommend_goods_1',$recommend_goods_1);          //门店推荐商品
        $this->assign('recommend_goods_2',$recommend_goods_2);          //门店推荐商品
        $this->assign('goods_label',$goods_label);                      //商品标签
        $this->assign('realname',session('_user_uid_.realname'));       //会员信息
        $this->assign('tui_goods',$tui_goods);                              //顶部导航栏推荐商品
        $this->assign('member',$member);                                //获取会员信息

        return $this->fetch('index');
    }

    /**
     * @Author  lingyun
     * @Desc    领取优惠券
     */
    public function receive_coupon(){
        $post = input('post.');
        if(session('_user_uid_.uid') == ''){
            $this->error('请先登录再领取优惠券',url('Login/loginin'));
        }
        $coupon = db('store_coupon')->where('id',$post['id'])->find();
        $data = [
            'store_id'=>$coupon['store_id'],
            'uid'=>session('_user_uid_.uid'),
            'coupon_id'=>$coupon['id'],
            'order_id'=>0,
            'receive_order_id'=>0,
            'type'=>1,          //关注券
            'cat_id'=>$coupon['cat_id'],
            'condition'=>$coupon['condition'],
            'morethan'=>$coupon['morethan'],
            'reduce'=>$coupon['reduce'],
            'use_start_time'=>$coupon['use_start_time'],
            'use_end_time'=>$coupon['use_end_time'],
            'addtime'=>time(),
            'price'=>$coupon['price'],
            'value'=>$coupon['value'],
            'is_used'=>0,
            'status'=>1
        ];
        db('user_ycard')->insert($data);
        db('store_coupon')->where('id',$post['id'])->setInc('send_num',1);      //更新优惠券领取数量
        $this->success('领取成功','');
    }

    /**
     * @Author  lignyun
     * @Desc    门店代金券
     */
    public function cash_coupon_list(){
        $store_id = session('store_id');
        $where_store_coupon = [
            'store_id'=>['eq',$store_id],
            'type'=>['eq',2],
            'status'=>['eq',1],
            'is_deleted'=>['eq',0]
        ];
        $list = db('store_coupon')->where($where_store_coupon)->select();
        $this->assign('list',$list);
        return $this->fetch('cash_coupon_list');
    }

    /**
     * @Author  lignyun
     * @Desc    购买代金券
     */
    public function post_cash_coupon(){
        $id = input('id');      //代金券id
        $where = [
            'uid'=>['eq',session('_user_uid_.uid')],
            'id'=>['eq',$id]
        ];
        $coupon = db('store_coupon')->where('id',$id)->find();
        $result = db('cash_coupon_list')->where($where)->field('count(*) as count,uid,cash_coupon_id')->find();
        if(!empty($result)){
            if($result['count'] >= $coupon['create_num']){
                $this->error('每人限购数量已达上限，不能再次购买',url('Index/store')."?id=".session('store_id'));
            }
        }
        $this->assign('coupon',$coupon);
        return $this->fetch('post_cash_coupon');
    }

    /**
     * @Author  lignyun
     * @Desc    余额购买代金券
     */
    public function buy_cash_coupon(){
        $post = input('param.');
        $uid = session("_user_uid_.uid");
        $where_user['uid'] = ['eq',$uid];
        //会员信息
        $member = db('user')->where($where_user)->field('uid,user_money,realname,level_point,pay_points')->find();

        $where_coupon['id'] = ['eq',$post['id']];
        //代金券信息
        $coupon = db('store_coupon')->where($where_coupon)->find();

        if($coupon['price']>$member['user_money']){
            $this->error('您当前的余额已不足，请选择其他付款方式','');
        }
        $data_arr = [
            'order_sn'=>create_order_sn($uid),
            'uid'=>$uid,
            'cash_coupon_id'=>$post['id'],
            'store_id'=>session('store_id'),
            'pay_time'=>time(),
            'pay_type'=>$post['pay_type'],
            'pay_status'=>1,
            'price'=>$coupon['price'],
            'remark'=>'支付成功',
            'addtime'=>time()
        ];
        db('cash_coupon_list')->insert($data_arr);
        $data_arr1 = [
            'uid'=>$uid,
            'store_id'=>session('store_id'),
            'order_sn'=>$data_arr['order_sn'],
            'pay_time'=>time(),
            'pay_status'=>1,
            'pay_type'=>3,
            'amount'=>$coupon['price'],
            'cur_amount'=>$member['user_money'] - $coupon['price'],
            'sign'=>2,
            'charge_cn'=>'购买代金券',
            'addtime'=>time()
        ];
        db('user_wallet_log')->insert($data_arr1);
        $where_point_rule['id'] = ['eq',2];
        $point_rule = db('sys_point')->where($where_point_rule)->find();
        //变更的积分
        $point = ceil($coupon['price']/10);
        $data_arr2 = [
            'uid'=>$uid,
            'store_id'=>session('store_id'),
            'uidtype'=>1,
            'signid'=>2,
            'type'=>1,
            'point'=>$point,
            'curpoint'=>$member['pay_points']+$point,
            'type_cn'=>'购买代金券赠送积分',
            'remark'=>'购买代金券赠送积分',
            'addtime'=>time(),
        ];
        db('user_point_log')->data($data_arr2)->insert();
        $cur_level_point = $member['level_point']+$point;
        $cur_pay_point = $member['pay_points']+$point;
        $point_rule = db('sys_level')->select();
        $level = userLevel($point_rule,$cur_level_point);
        $data_arr3 = [
            'uid'=>$uid,
            'user_money'=>$member['user_money']-$coupon['price'],
            'level_point'=>$cur_level_point,
            'pay_points'=>$cur_pay_point,
        ];
        db('user')->data($data_arr3)->update();
        $this->success('支付成功','');
    }

    /**
     * @Author  lingyun
     * @Desc    搜索艺术美食
     */
    public function search(){
        $cur_city = db('city')->where('key',cookie('city_key'))->value('value');        //当前城市

        $this->assign('realname',session('_user_uid_.realname'));
        $this->assign('cur_city',$cur_city);
        $this->assign('url',request()->url(true));

        $sql = "SELECT id,name,logo,cat_id FROM ys_goods AS a WHERE 5> (SELECT COUNT(*) FROM ys_goods WHERE cat_id=a.cat_id AND id>a.id) AND a.is_online=1 ORDER BY a.id DESC";
        $tui_goods = Db::query($sql);
        $this->assign('tui_goods',$tui_goods);

        $key = input('key');

        //查询条件
        $where_goods_arr = [
            'a.store_id'=>0,
            'a.is_deleted'=>0,
            'a.is_online'=>1,         //恢复线上线下状态 @lingyun  2018-03-29
            'a.status'=>1,
//            'a.cat_id'=>$cate_id,
            'a.name'=>['like','%'.$key.'%'],
        ];

        //查询会员等级价格
        $join = [
            ['ys_sys_level b','a.member_level_id=b.id','LEFT']
        ];

        if(!is_mobile() && !is_weixin()){
            $goods = db('goods')->alias('a')->join($join)->field('a.*,b.title,b.css_color')->where($where_goods_arr)->paginate(8,false,['query'=>request()->param()]);     //商品列表
            $page = $goods->render();               //分页数据
            $all_goods = $goods->all();
        }else{
            $goods = db('goods')->alias('a')->join($join)->field('a.*,b.title,b.css_color')->where($where_goods_arr)->paginate(10000,false,['query'=>request()->param()]);     //商品列表
            $page = $goods->render();               //分页数据
            $all_goods = $goods->all();
        }

        //搜索结果
//        $goods = db('goods')->where('name','like','%'.$key.'%')->paginate(2,false,['query'=>request()->param()]);
        //商品顶级分类
        $category = db('goods_category')->where(['status'=>1,'is_deleted'=>0,'is_exp'=>0])->select();
        //扩展分类
        $exp_category = db('goods_category')->where(['status'=>1,'is_deleted'=>0,'is_exp'=>1])->select();

        $exp_cate = input('exp_cate');          //门店商品扩展分类
        $realname = db('user')->where('uid',session('_user_uid_.uid'))->value('realname');

        $this->assign('page',$page);
        $this->assign('goods',$goods);
        $this->assign('category',$category);
        $this->assign('exp_cate',$exp_cate);
        $this->assign('exp_category',$exp_category);
        $this->assign('city',cookie('city'));
        $this->assign('realname',session('realname'));
        $this->assign('cate_id',$category[0]['id']);
        $this->assign('cash_coupon',0);                         //不是代金券
        $this->assign('realname',$realname);                         //不是代金券
        $this->assign('all_goods',$all_goods);                         //不是代金券

        return $this->fetch('search');
    }

    /**
     * @Author  lingyun
     * @Desc    首页更多优惠券
     */
    public function more_coupon(){
        $store_id = cookie('store_id');
        if(empty(session('_user_uid_.uid'))){
            $this->redirect('Login/loginin');
        }
        if(empty($store_id)){       //没有选中门店 -- 区选择门店
            $this->redirect('Changestore/index');
        }
        $map_arr = [
            'store_id'=>$store_id,
            'type'=>1,
            'status'=>1,
            'is_deleted'=>0
            ];
            $coupon = db('store_coupon')->where($map_arr)->field('id,morethan,reduce,(select count(*) from ys_user_ycard where uid='.session("_user_uid_.uid").' and coupon_id=ys_store_coupon.id) as is_received')->select();

        $this->assign('coupon',$coupon);

        return $this->fetch('more_coupon');
    }

    /**
     * @Author  lingyun
     * @Desc    领取会员权益优惠券
     * 2018-03-23
     */
    public function get_qy_coupon(){
        $uid = session('_user_uid_.uid');
        if(empty($uid)){        //先去登录
            return json(['code'=>-1,'msg'=>'您好没有登录，请先去登录']);
        }
        $service = new IndexService();
        $res = $service->get_qy_coupon();      //获取权益优惠券

        if($res>0){
            return json(['code'=>1,'msg'=>'领取成功']);
        }else{
            return json(['code'=>0,'msg'=>'领取失败']);
        }
//        $data = [];                 //组合入库数据
//        foreach($coupon as $k=>$v){     //组合入库数据
//            $data[$k]['store_id'] = $v['store_id'];
//            $data[$k]['coupon_id'] = $v['id'];
//            $data[$k]['uid'] = $uid;
//            $data[$k]['type'] = 3;
//            $data[$k]['cat_id'] = $v['cat_id'];
//            $data[$k]['condition'] = $v['condition'];
//            $data[$k]['morethan'] = $v['morethan'];
//            $data[$k]['reduce'] = $v['reduce'];
//            $data[$k]['use_start_time'] = $v['use_start_time'];
//            $data[$k]['use_end_time'] = $v['use_end_time'];
//            $data[$k]['addtime'] = time();
//            $data[$k]['price'] = $v['price'];
//            $data[$k]['value'] = $v['value'];
//            $data[$k]['is_used'] = 0;
//            $data[$k]['status'] = 1;
//        }
//
//        $res = db('user_ycard')->insertAll($data);      //批量新增


    }

}
